package com.example.http.httpclient;

import java.io.IOException;
import java.util.UUID;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;




public abstract class BusinessDYJ {

	/**
	 * 代理商编号
	 * 测试期间编号为3821
	 * */
	private String wAgent;
	
	/**
	 * 代理商密钥
	 * 测试期间a8b8c8d8e8f8g8h8
	 * */
	private String secretKey;
	
	/**交易申请码*/
	protected String wAction;
	
	/**本地交易序号*/
	private String wMsgID;
	
	/**业务参数*/
	protected String wParam;
	
	/**摘要*/
	private String wSign;
	
	/**请求后的响应*/
	private ActionResultXML actionResultXML;
	
	/**地址*/
	private String url;
	
	private transient final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Override
	public String toString() {
		StringBuffer sb=new StringBuffer();
		sb.append("url:").append(url).append("\n").
		append("wAgent:").append(wAgent).append("\n").
		append("secretKey:").append(secretKey).append("\n").
		append("wAction:").append(wAction).append("\n").
		append("wMsgID:").append(wMsgID).append("\n").
		append("wParam:").append(wParam).append("\n").
		append("wSign:").append(wSign);
		return sb.toString();
	}
	
	/**
	 * @param config 大赢家的帐户配置
	 */
	protected BusinessDYJ(IVenderConfig config){
		this.wAgent = config.getVenderAgentCode();
		this.secretKey = config.getVenderSignKey();
		this.url = config.getVenderRequestUrl();
	}
	
	/**构造业务数据*/
	protected abstract void buildParam();
	
	/**创建业务序号*/
	private void buildWMsgID(){
		this.wMsgID = System.currentTimeMillis()+UUID.randomUUID().toString();
	}
	
	/**计算摘要*/
	public void buildWSign(){
		buildParam();
		buildWMsgID();
		this.wSign ="";
	}
	
	
	/**获取大赢家的响应*/
	public ActionResultXML getResponseResult() throws Exception{
		buildWSign();
		HttpClientParams clientParams = new HttpClientParams();
		clientParams.setParameter(HttpClientParams.HTTP_CONTENT_CHARSET, "gb2312");
		clientParams.setSoTimeout(10000);
		HttpClient client = new HttpClient(clientParams);
		PostMethod postMethod = new PostMethod(url);
		postMethod.addParameters(new NameValuePair[] {
				new NameValuePair("wAgent", wAgent),
				new NameValuePair("wAction", wAction), 
				new NameValuePair("wMsgID", wMsgID),
				new NameValuePair("wSign", wSign),
				new NameValuePair("wParam", wParam)});
		try {
			postMethod.setRequestHeader("Connection", "close");
			//int statusCode = httpClient.executeMethod(postMethod);
			client.executeMethod(postMethod);
			logger.info("大赢家返回: {}", postMethod.getResponseBodyAsString());
			
			this.actionResultXML = ActionResultXML.getInstance(postMethod.getResponseBodyAsStream(), "gb2312");
		} catch (Exception e) {
			logger.error("大赢家返回: {}", postMethod.getResponseBodyAsString());
			logger.error(e.getMessage(), e);
			throw e;
		} finally{
			postMethod.releaseConnection();
			if (postMethod.getResponseBodyAsString() != null) {
				logger.info("\n本次请求:\n{}\n本次响应:{}",this,postMethod.getResponseBodyAsString().toString());				
			}
		}
		return this.actionResultXML;
	}
	//get方法
	public static void get(){
		//构造HttpClient的实例
		  HttpClient httpClient = new HttpClient();
		  //创建GET方法的实例
		  GetMethod getMethod = new GetMethod("http://www.ibm.com");
		  //使用系统提供的默认的恢复策略
		  getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
		    new DefaultHttpMethodRetryHandler());
		  try {
		   //执行getMethod
		   int statusCode = httpClient.executeMethod(getMethod);
		   if (statusCode != HttpStatus.SC_OK) {
		    System.err.println("Method failed: "
		      + getMethod.getStatusLine());
		   }
		   //读取内容 
		   byte[] responseBody = getMethod.getResponseBody();
		   //处理内容
		   System.out.println(new String(responseBody));
		  } catch (HttpException e) {
		   //发生致命的异常，可能是协议不对或者返回的内容有问题
		   System.out.println("Please check your provided http address!");
		   e.printStackTrace();
		  } catch (IOException e) {
		   //发生网络异常
		   e.printStackTrace();
		  } finally {
		   //释放连接
		   getMethod.releaseConnection();
		  }
		 

	}

	/**获取大赢家的竞彩足球检票结果响应*/
	public String getJcResponseResult() throws Exception{
		buildWSign();
		HttpClientParams clientParams = new HttpClientParams();
		clientParams.setParameter(HttpClientParams.HTTP_CONTENT_CHARSET, "gb2312");
		clientParams.setSoTimeout(10000);
		HttpClient client = new HttpClient(clientParams);
		PostMethod postMethod = new PostMethod(url);
		postMethod.addParameters(new NameValuePair[] {
				new NameValuePair("wAgent", wAgent),
				new NameValuePair("wAction", wAction), 
				new NameValuePair("wMsgID", wMsgID),
				new NameValuePair("wSign", wSign),
				new NameValuePair("wParam", wParam)});
		try {
			postMethod.setRequestHeader("Connection", "close");
			client.executeMethod(postMethod);
			logger.info("大赢家竞彩足球检票返回: {}", postMethod.getResponseBodyAsString());
		} catch (Exception e) {
			logger.error("大赢家竞彩足球检票返回: {}", postMethod.getResponseBodyAsString());
			logger.error(e.getMessage(), e);
			throw e;
		} 
		finally{
			postMethod.releaseConnection();
			logger.info("\n本次请求:\n{}\n本次响应:{}",this,postMethod.getResponseBodyAsString().toString());
		}
		return postMethod.getResponseBodyAsString();
	}
	
	/**获取大赢家的电子赛车奖金对照表信息查询响应*/
	public String getXyscResponseResult() throws Exception{
		buildWSign();
		HttpClientParams clientParams = new HttpClientParams();
		clientParams.setParameter(HttpClientParams.HTTP_CONTENT_CHARSET, "gb2312");
		clientParams.setSoTimeout(10000);
		HttpClient client = new HttpClient(clientParams);
		PostMethod postMethod = new PostMethod(url);
		postMethod.addParameters(new NameValuePair[] {
				new NameValuePair("wAgent", wAgent),
				new NameValuePair("wAction", wAction), 
				new NameValuePair("wMsgID", wMsgID),
				new NameValuePair("wSign", wSign),
				new NameValuePair("wParam", wParam)});
		try {
			postMethod.setRequestHeader("Connection", "close");
			client.executeMethod(postMethod);
			logger.info("大赢家电子赛车奖金对照表返回: {}", postMethod.getResponseBodyAsString());
		} catch (Exception e) {
			logger.error("大赢家电子赛车奖金对照表返回: {}", postMethod.getResponseBodyAsString());
			logger.error(e.getMessage(), e);
			throw e;
		} 
		finally{
			postMethod.releaseConnection();
			logger.info("\n本次请求:\n{}\n本次响应:{}",this,postMethod.getResponseBodyAsString().toString());
		}
		return postMethod.getResponseBodyAsString();
	}
	
	public String getWAgent() {
		return wAgent;
	}

	public String getSecretKey() {
		return secretKey;
	}

	public String getWAction() {
		return wAction;
	}

	public String getWMsgID() {
		return wMsgID;
	}

	public String getWParam() {
		return wParam;
	}

	public String getWSign() {
		return wSign;
	}
}
